import 'package:flutter/material.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:csv/csv.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'ppg_service.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: PPGChartPage(),
    );
  }
}

class PPGChartPage extends StatefulWidget {
  @override
  _PPGChartPageState createState() => _PPGChartPageState();
}

class _PPGChartPageState extends State<PPGChartPage> {
  List<double> irValues = [];
  List<double> redValues = [];
  Map<String, dynamic> results = {};
  bool isLoading = true;
  String errorMessage = '';

  @override
  void initState() {
    super.initState();
    loadAndProcessData();
  }

  Future<void> loadAndProcessData() async {
    try {
      // 加载 CSV 文件
     // 更健壮的读取方式
     // 在 loadAndProcessData 开头添加：
      final byteData = await rootBundle.load('assets/data.csv');
      final buffer = byteData.buffer;
      final csvString = String.fromCharCodes(buffer.asUint8List(
        byteData.offsetInBytes, 
        byteData.lengthInBytes
      ));
      final csvParser = CsvToListConverter();
      List<List<dynamic>> rawData = csvParser.convert(csvString, eol: '\n');

        // 跳过第一行标题
      if (rawData.isNotEmpty) {
        rawData.removeAt(0);
      }

      // 提取 IR 和 Red 值
      irValues = rawData.map((row) => double.parse(row[1].toString())).toList();
      redValues = rawData.map((row) => double.parse(row[2].toString())).toList();
      print('irValues: $irValues.length, redValues: $redValues.length');

      // 确保数据长度正确
      // if (irValues.length != PPGService.BUFFER_SIZE || 
      //     redValues.length != PPGService.BUFFER_SIZE) {
      //   throw Exception('数据长度不符合要求');
      // }

      // 计算指标
      final metrics = PPGService.calculateMetrics(irValues, redValues);
      
      setState(() {
        results = metrics;
        isLoading = false;
      });

    } catch (e) {
      setState(() {
        errorMessage = '数据加载失败: $e';
        isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('PPG 数据分析')),
      body: _buildContent(),
    );
  }

  Widget _buildContent() {
    if (errorMessage.isNotEmpty) {
      return Center(child: Text(errorMessage));
    }

    if (isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    return Column(
      children: [
        _buildMetricsDisplay(),
        Expanded(
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: LineChart(
              LineChartData(
                gridData: const FlGridData(show: true),
                titlesData: const FlTitlesData(show: false),
                borderData: FlBorderData(show: true),
                lineBarsData: [
                  LineChartBarData(
                    spots: List.generate(
                      irValues.length,
                      (i) => FlSpot(i.toDouble(), irValues[i]),
                    ),
                    isCurved: false,
                    dotData: const FlDotData(show: false),
                    color: Colors.blue,
                  ),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildMetricsDisplay() {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildMetricRow(
            '血氧饱和度:',
            '${results['spo2']?.toStringAsFixed(1)}%',
            results['spo2Valid'] == 1 ? Colors.green : Colors.red,
          ),
          const SizedBox(height: 8),
          _buildMetricRow(
            '心率:',
            '${results['hr']?.toStringAsFixed(1)} bpm',
            results['hrValid'] == 1 ? Colors.green : Colors.red,
          ),
        ],
      ),
    );
  }

  Widget _buildMetricRow(String label, String value, Color color) {
    return Row(
      children: [
        Text(label, style: const TextStyle(fontSize: 16)),
        const SizedBox(width: 8),
        Text(value, style: TextStyle(fontSize: 16, color: color)),
        const SizedBox(width: 8),
        Icon(
          color == Colors.green ? Icons.check_circle : Icons.error,
          color: color,
          size: 20,
        )
      ],
    );
  }
}